package com.horay.springbootdemo.hibernate.validator.common;

import com.horay.springbootdemo.common.exception.BizException;
import com.horay.springbootdemo.common.result.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * 全局异常处理程序
 *
 * @author heyingcheng
 * @date 2019/10/1 21:02
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static int DUPLICATE_KEY_CODE = 1001;
    private static int PARAM_FAIL_CODE = 1002;
    private static int VALIDATION_CODE = 1003;

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BizException.class)
    public ResultBody<String> handleRRException(BizException e) {
        log.error(e.getMessage(), e);
        return new ResultBody(e.getCode(), e.getMessage());
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBody handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return new ResultBody(PARAM_FAIL_CODE, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public ResultBody handleValidationException(ValidationException e) {
        log.error(e.getMessage(), e);
        return new ResultBody(VALIDATION_CODE, e.getCause().getMessage());
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultBody handleConstraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        return new ResultBody(PARAM_FAIL_CODE, e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultBody handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResultBody(HttpServletResponse.SC_NOT_FOUND, "路径不存在, 请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResultBody handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return new ResultBody(DUPLICATE_KEY_CODE, "数据重复, 请检查后提交");
    }


    @ExceptionHandler(Exception.class)
    public ResultBody handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResultBody(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "系统繁忙, 请稍后再试");
    }
}
